import {defineStore} from 'pinia'
import {useRouter} from "vue-router";
interface stateInter {
    token: string,
    menus: {
        id:number,
        title:string,
        path:string,
        name:string,
        icon:string,
        parentId:number,
        children:stateInter["menus"][]
    }[],
    userInfo: {
        id: number,
        account: string,
        name: string,
        phone: string,
        money: number,
        address: string,
        avator: string,
        createTime: string,
        updateTime: string,
    }
}

// 你可以任意命名 `defineStore()` 的返回值，但最好使用 store 的名字，同时以 `use` 开头且以 `Store` 结尾。
// (比如 `useUserStore`，`useCartStore`，`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useAppStore = defineStore('app', {
    state: (): stateInter => ({
        token: "",
        userInfo: {} as stateInter["userInfo"],
        menus: [] as stateInter["menus"]
    }),
    //开启持久化
    persist: {
        key: 'app',
        storage: localStorage,
        serializer: {
            serialize: JSON.stringify,
            deserialize: JSON.parse
        }
    },
    getters: {
        getUserInfo(state) {
            return state.userInfo
        },
        getMenus(state) {   
            return state.menus
        },
        getToken(state) {
            return state.token
        }
    },
    actions: {
        setUserInfo(userInfo: stateInter["userInfo"]) {
            this.userInfo = userInfo
        },
        setMenus(menus: stateInter["menus"]) {
            this.menus = menus
        },
        setToken( token: string) {
            this.token = token
        },
        logout(){
            const router = useRouter()
            this.userInfo = {} as stateInter["userInfo"]
            this.menus = [] as stateInter["menus"]
            this.token = "" as stateInter["token"]
            window.location.reload()
        }
    }
})